<script setup lang="tsx">
import type { SelectOption } from 'naive-ui';
import { computed, watch } from 'vue';
import type { LastLevelRouteKey } from '@elegant-router/types';
import { useForm } from '@sa/alova/client';
import { getLocalIcons } from '@/utils/icon';
import SvgIcon from '@/components/_builtin/svg-icon/index.vue';
import { $t } from '@/locales';
import { createMenu, fetchMenu, updateMenu } from '@/service/api/manage';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import {
  getLayoutAndPage,
  getPathParamFromRoutePath,
  getRoutePathByRouteName,
  getRoutePathWithParam,
  transformLayoutAndPageToComponent
} from './shared';

defineOptions({
  name: 'MenuOperateDrawer'
});

export type OperateType = NaiveUI.TableOperateType;

interface Props {
  /** the type of operation */
  operateType: OperateType;
  /** the edit menu data or the parent menu data when adding a child menu */
  rowData?: Api.Manage.Menu | null;
  /** all pages */
  allPages: string[];
}

const props = defineProps<Props>();

type Model = Api.Manage.Menu & {
  query: NonNullable<Api.Manage.Menu['query']>;
  layout: string;
  page: string;
  pathParam: string;
};

interface Emits {
  (e: 'submitted', data: Api.Manage.Menu): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<OperateType, string> = {
    add: $t('page.manage.menu.addMenu'),
    edit: $t('page.manage.menu.editMenu')
  };
  return titles[props.operateType];
});

function createDefaultModel(): Api.Manage.Menu {
  return {
    id: 0,
    parentId: 0,
    type: 1,
    name: '',
    i18nKey: null,
    routeName: '',
    routePath: '',
    pathParam: '',
    component: '',
    icon: '',
    iconType: '1',
    layout: '',
    page: '',
    status: 1,
    hide: '0',
    sortRank: 0,
    href: '',
    keepAlive: '1',
    multiTab: '0',
    activeMenu: '' as LastLevelRouteKey,
    fixedIndexInTab: -1,
    query: ''
  };
}

const {
  loading: submitting,
  reset,
  send: submit,
  form: model
} = useForm(formData => (props.operateType === 'add' ? createMenu(formData) : updateMenu(formData)), {
  initialForm: createDefaultModel(),
  resetAfterSubmitting: true
});

type RuleKey = Extract<keyof Model, 'name' | 'status' | 'routeName' | 'routePath'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  name: defaultRequiredRule,
  status: defaultRequiredRule,
  routeName: defaultRequiredRule,
  routePath: defaultRequiredRule
};

const localIcons = getLocalIcons();
const localIconOptions = localIcons.map<SelectOption>(item => ({
  label: () => (
    <div class="flex-y-center gap-16px">
      <SvgIcon localIcon={item} class="text-icon" />
      <span>{item}</span>
    </div>
  ),
  value: item
}));

const showLayout = computed(() => model.value.parentId === 0 || model.value.parentId === null);

const showPage = computed(() => model.value.type === 2);

const pageOptions = computed(() => {
  const allPages = [...props.allPages];

  if (model.value.routeName && !allPages.includes(model.value.routeName)) {
    allPages.unshift(model.value.routeName);
  }

  const opts: Common.Option[] = allPages.map(page => ({
    label: page,
    value: page
  }));

  return opts;
});

const layoutOptions: Common.Option[] = [
  {
    label: 'base',
    value: 'base'
  },
  {
    label: 'blank',
    value: 'blank'
  }
];

const isEdit = computed(() => props.operateType === 'edit');

async function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (!props.rowData) return;

  if (props.operateType === 'add') {
    reset();

    if (model.value.type === 1) {
      const { id } = props.rowData;
      Object.assign(model.value, { parentId: id });
    }

    return;
  }

  if (props.operateType === 'edit') {
    const data = await fetchMenu({ id: props.rowData?.id });
    if (data) {
      const { component, ...rest } = data;
      const { layout, page } = getLayoutAndPage(component);
      const { path, param } = getPathParamFromRoutePath(rest.routePath);
      Object.assign(model.value, rest, { layout, page, routePath: path, pathParam: param });
    }
  }
}

function closeDrawer() {
  visible.value = false;
}

function handleUpdateRoutePathByRouteName() {
  if (model.value.routeName) {
    model.value.routePath = getRoutePathByRouteName(model.value.routeName);
  } else {
    model.value.routePath = '';
  }
}

function handleUpdateI18nKeyByRouteName() {
  if (model.value.routeName) {
    model.value.i18nKey = `route.${model.value.routeName}` as App.I18n.I18nKey;
  } else {
    model.value.i18nKey = null;
  }
}

function getSubmitParams() {
  const { layout, page, pathParam } = model.value;

  const component = transformLayoutAndPageToComponent(layout, page);
  const routePath = getRoutePathWithParam(model.value.routePath, pathParam);

  model.value.component = component;
  model.value.routePath = routePath;

  return model;
}

async function handleSubmit() {
  await validate();

  getSubmitParams();

  await submit();
  window.$message?.success(isEdit.value ? $t('common.updateSuccess') : $t('common.addSuccess'));
  closeDrawer();
  emit('submitted', model.value);
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});

watch(
  () => model.value.routeName,
  () => {
    handleUpdateRoutePathByRouteName();
    handleUpdateI18nKeyByRouteName();
  }
);
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" width="sm:450 s:360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" :label-width="80">
        <NGrid>
          <NFormItemGi span="24" label="上级菜单" path="type">
            <PorTreeSelect
              v-model:value="model.parentId"
              url="/permission/menu/tree?types=1"
              value-to-number
              clearable
            ></PorTreeSelect>
          </NFormItemGi>
          <NFormItemGi span="24" label="类型" path="type">
            <PorDictRadio v-model:value="model.type" dict-code="system_menu_type" value-to-number></PorDictRadio>
          </NFormItemGi>

          <NFormItemGi span="24" label="名称" path="name">
            <NInput v-model:value="model.name" placeholder="请输入名称" />
          </NFormItemGi>
          <NFormItemGi span="24" label="路由名称" path="routeName">
            <NInput v-model:value="model.routeName" placeholder="请输入路由名称" />
          </NFormItemGi>
          <NFormItemGi span="24" label="路由路径" path="routePath">
            <NInput v-model:value="model.routePath" disabled placeholder="请输入路由路径" />
          </NFormItemGi>
          <NFormItemGi span="12" label="路由参数">
            <NInput v-model:value="model.pathParam" placeholder="请输入路由参数" />
          </NFormItemGi>
          <NFormItemGi span="12" label="查询参数">
            <NInput v-model:value="model.query" placeholder="请输入查询参数，示例 a=1&b=2" />
          </NFormItemGi>
          <NFormItemGi v-if="showLayout" span="24" label="布局组件" path="layout">
            <NSelect v-model:value="model.layout" :options="layoutOptions" placeholder="请选择布局组件" />
          </NFormItemGi>
          <NFormItemGi v-if="showPage" span="24" label="页面组件" path="page">
            <NSelect v-model:value="model.page" :options="pageOptions" placeholder="请选择页面组件" />
          </NFormItemGi>
          <NFormItemGi span="24" label="外链" path="href">
            <NInput v-model:value="model.href" placeholder="请输入外链" />
          </NFormItemGi>
          <NFormItemGi span="12" label="图标类型" path="iconType">
            <PorDictRadio v-model:value="model.iconType" dict-code="menu_icon_type"></PorDictRadio>
          </NFormItemGi>
          <NFormItemGi span="12" label="图标" path="icon">
            <template v-if="model.iconType === '1'">
              <NInput v-model:value="model.icon" placeholder="请输入图标" class="flex-1">
                <template #suffix>
                  <SvgIcon v-if="model.icon" :icon="model.icon" class="text-icon" />
                </template>
              </NInput>
            </template>
            <template v-if="model.iconType === '2'">
              <NSelect v-model:value="model.icon" placeholder="请输入本地图标" :options="localIconOptions" />
            </template>
          </NFormItemGi>
          <NFormItemGi span="12" label="状态" path="status">
            <PorDictRadio v-model:value="model.status" dict-code="common_status" value-to-number></PorDictRadio>
          </NFormItemGi>
          <NFormItemGi span="12" label="国际化Key" path="i18nKey">
            <NInput v-model:value="model.i18nKey" placeholder="请输入国际化Key" />
          </NFormItemGi>

          <NFormItemGi span="12" label="隐藏菜单" path="hide">
            <PorDictRadio v-model:value="model.hide" dict-code="common_yes_no"></PorDictRadio>
          </NFormItemGi>
          <NFormItemGi span="12" label="缓存路由" path="keepAlive">
            <PorDictRadio v-model:value="model.keepAlive" dict-code="common_yes_no"></PorDictRadio>
          </NFormItemGi>
          <NFormItemGi span="12" label="多页签" path="multiTab">
            <PorDictRadio v-model:value="model.multiTab" dict-code="common_yes_no"></PorDictRadio>
          </NFormItemGi>
          <NFormItemGi span="12" label="排序号" path="sortRank">
            <NInputNumber v-model:value="model.sortRank" placeholder="请输入排序号" />
          </NFormItemGi>
          <NFormItemGi span="12" label="页签序号" path="fixedIndexInTab">
            <NInputNumber v-model:value="model.fixedIndexInTab" placeholder="请输入固定在页签中的序号" />
          </NFormItemGi>
        </NGrid>
      </NForm>
      <template #footer>
        <NSpace :size="12" justify="end">
          <NButton quaternary @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" :loading="submitting" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>
